# -*- coding: utf-8 -*-
# @File:     membership.py
# @Author:
# @DateTime: 2025/06/05/16:07
import datetime
from typing import Optional, Union, Any

from fastapi.encoders import jsonable_encoder
from sqlalchemy import or_
from sqlalchemy.orm import Session
from app.db.database import get_db
from app.models.system import Users
from app.utils import security
from app.utils.custom_response import success_response
from fastapi import APIRouter, Query, Body, Path, Depends, Request
from pydantic import BaseModel, Field

from app.models.generate import UserMembership
from app.utils.curd_base import ModelCRUD

router = APIRouter()


class CRUDUserMembership(ModelCRUD):
    model = UserMembership

    @staticmethod
    def serializer(queryset, only: tuple = (), date_format: str = None, datetime_format: str = None,
                   time_format: str = None):
        li = list()
        for instance in queryset:
            data = instance.to_dict(only=only, date_format=date_format, datetime_format=datetime_format, time_format=time_format)
            data['user_name'] = instance.user.username
            li.append(data)
        return li


class CreateUserMembership(BaseModel):
    total: int = Field(description='总数')
    user_id: int = Field(description='用户')
    task_num: Optional[int] = Field(description='任务数', default=1)
    priority: Optional[int] = Field(description='优先级', default=5)
    start_time: Optional[str] = Field(default=None, description='开始时间')
    expire_time: Optional[str] = Field(default=None, description='过期时间')
    grade: Optional[int] = Field(default=1, description='等级')


class ResUserMembership(CreateUserMembership):
    use_number: Optional[int] = Field(description='使用数量')


class DeleteModel(BaseModel):
    id: list[int] = Field(description='ID列表')


@router.post("/user_membership", summary="新增用户套餐", response_model=ResUserMembership, name='新增用户套餐')
async def user_membership(
    *,
    db: Session = Depends(get_db),
    req_data: CreateUserMembership,
    current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    crud = CRUDUserMembership()
    instance = crud.create(db, data=req_data)
    only = ('id', 'total', 'use_number', 'user_id', 'task_num', 'priority', 'start_time', 'expire_time', 'grade')
    data = instance.to_dict(only=only, datetime_format='%Y-%m-%d %H:%M:%S')
    data['user_name'] = instance.user.username
    return success_response(data=data)


def search_info_filter(queryset, name, value):

    return queryset.filter(Users.username.contains(value))


able_filter_list = [
    {'name': 'user_id', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': '等于user', 'type': int, 'method': None, 'required': False},
    {'name': 'search_info', 'source_filed': 'user_id', 'lookup_expr': 'eq', 'label': 'username', 'type': str, 'method': search_info_filter, 'required': False},
]


@router.get("/user_membership", summary="获取用户套餐", response_model=ResUserMembership, name='获取用户套餐')
async def user_membership(
        request: Request,
        *,
        db: Session = Depends(get_db),
        page: int = Query(1, description='页码', ge=1),
        page_size: int = Query(10, description='页面大小', le=50, ge=1),
        user_id: int = Query(None, description='用户ID'),
        search_info: str = Query(None, description='搜索内容'),
        current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    order_by_fields = ('-id',)
    crud = CRUDUserMembership()

    queryset, total = crud.get_page_queryset(db, page=page, page_size=page_size, req_data=request.query_params, able_filter_list=able_filter_list, order_by_fields=order_by_fields)
    only = ('id', 'total', 'use_number', 'user_id', 'task_num', 'priority', 'start_time', 'expire_time', 'grade')
    items = crud.serializer(queryset, only=only, datetime_format='%Y-%m-%d %H:%M:%S')
    resp = {
        "list": items,
        'total': total
    }
    return success_response(data=resp)


@router.put("/user_membership/{instance_id}", summary="修改用户套餐", response_model=ResUserMembership, name='修改用户套餐')
async def user_membership(
        request: Request,
        *,
        db: Session = Depends(get_db),
        instance_id,
        req_data: CreateUserMembership,
        current_user: Users = Depends(security.verify_admin_permission),
) -> Any:
    crud = CRUDUserMembership()
    instance = crud.get_object(db, instance_id)
    # req_data.user_id = instance_id
    instance = crud.update(db, instance=instance, data=req_data)

    only = ('id', 'total', 'use_number', 'user_id', 'task_num', 'priority', 'start_time', 'expire_time', 'grade')
    data = instance.to_dict(only=only, datetime_format='%Y-%m-%d %H:%M:%S')
    data['user_name'] = instance.user.username

    return success_response(data=data)


@router.delete("/user_membership", summary="删除用户套餐", response_model=ResUserMembership, name='删除用户套餐')
async def user_membership(
        *,
        db: Session = Depends(get_db),
        req_data: DeleteModel,
        current_user: Users = Depends(security.verify_admin_permission),
) -> Any:

    crud = CRUDUserMembership()
    crud.delete(db, req_body=req_data)
    return success_response(data={})


# --------------------------------------------------------------


@router.get("/get_membership", summary="用户获取套餐", response_model=ResUserMembership, name='用户获取套餐')
async def user_membership(
        *,
        db: Session = Depends(get_db),
        current_user: Users = Depends(security.verify_access_token),
) -> Any:

    crud = CRUDUserMembership()
    now_time = datetime.datetime.now()
    instance = db.query(crud.model).filter(crud.model.is_delete == 0, crud.model.start_time <= now_time,
                                           crud.model.expire_time >= now_time, crud.model.user_id == int(current_user.id)).first()

    print(instance)

    if not instance:
        instance = db.query(crud.model).filter(crud.model.start_time == None, crud.model.expire_time == None, crud.model.user_id == int(current_user.id)).first()  # type: ignore

    print(current_user.id, instance)
    if instance:
        only = ('id', 'total', 'use_number', 'task_num', 'start_time', 'expire_time', 'grade')
        data = instance.to_dict(only=only, datetime_format='%Y-%m-%d %H:%M:%S')
    else:
        data = {}
    return success_response(data=data)




